<template>
  <div class="cart-container">
    <el-page-header @back="$router.go(-1)">
      <template #content>
        <span class="text-large font-600 mr-3">购物车</span>
      </template>
    </el-page-header>

    <el-skeleton :rows="6" animated v-if="loading" />
    <el-alert v-if="error" type="error" :title="error.message" show-icon />

    <el-table :data="cartItems" v-if="!loading && !error" style="width: 100%" empty-text="购物车空空如也~">
      <el-table-column width="60">
        <template #header>
          <el-checkbox v-model="selectAll" />
        </template>
        <template #default="{ row }">
          <el-checkbox v-model="row.selected" @change="updateSelected(row)" />
        </template>
      </el-table-column>

      <el-table-column label="商品" width="400">
        <template #default="{ row }">
          <div class="product-info">
            <el-image
              :src="apiBase + '/product_images/' + row.product_image"
              class="product-image"
              fit="contain"
              :preview-src-list="[apiBase + '/product_images/' + row.product_image]"
            />
            <span class="product-name">{{ row.productName }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="单价" width="150">
        <template #default="{ row }">
          ¥{{ row.productPrice.toFixed(2) }}
        </template>
      </el-table-column>

      <el-table-column label="数量" width="200">
        <template #default="{ row }">
          <div class="quantity-controls">
            <el-button @click="updateQuantity(row, 0)">-</el-button>
            <el-input
              v-model="row.quantity"
              class="quantity-input"
              :min="1"
              :max="row.productStock"
            />
            <el-button @click="updateQuantity(row, 1)">+</el-button>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="小计" width="150">
        <template #default="{ row }">
          ¥{{ (row.quantity * row.productPrice).toFixed(2) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button 
            type="danger" 
            @click="handleDelete(row.productId)"
            :loading="row.deleting"
          >删除</el-button>
          <el-button
            type="success"
            @click="handleBuyNow(row)"
            :loading="row.buyNowLoading"
          >购买</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getToken } from '@/utils/storage';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();

const handleBuyNow = async (row) => {
  try {
    row.buyNowLoading = true;
    
    const deliveryRes = await axios.get(`${apiBase.value}/user/delivery`, {
      headers: { Authorization: `Bearer ${getToken()}` }
    });

    const orderRes = await axios.post(`${apiBase.value}/order`, {
      productId: row.productId,
      quantity: row.quantity,
      deliveryInfo: deliveryRes.data
    }, {
      headers: { Authorization: `Bearer ${getToken()}` }
    });

    router.push({
      path: '/payment',
      query: {
        orderId: orderRes.data.order_id,
        productName: row.productName,
        productPrice: row.productPrice,
        totalAmount: orderRes.data.order_total_amount,
        quantity: row.quantity,
        productImage: row.product_image
      }
    });
  } catch (err) {
    ElMessage.error('创建订单失败：' + (err.response?.data?.message || err.message));
  } finally {
    row.buyNowLoading = false;
  }
};
const apiBase = ref(import.meta.env.VITE_API_BASE || '');
const cartItems = ref([]);
const loading = ref(true);
const error = ref(null);
const selectAll = ref(false);

const handleDelete = async (productId) => {
  try {
    const token = getToken();
    await axios.delete(`${apiBase.value}/cart/${productId}`, {
      headers: { Authorization: `Bearer  ${token}` }
    });
    ElMessage.success('删除成功');
    await fetchCartData();
  } catch (err) {
    ElMessage.error('删除商品失败');
  }
};

const fetchCartData = async () => {
  try {
    const token = getToken();
    if (!token) {
      ElMessage.error('请先登录');
      return;
    }

    const { data } = await axios.get(`${apiBase.value}/cart`, {
      headers: { Authorization: `Bearer  ${token}` }
    });

    cartItems.value = data.map(item => ({
      ...item,
      selected: item.selected || false,
      buyNowLoading: false
    }));
  } catch (err) {
    error.value = err;
    ElMessage.error('获取购物车数据失败');
  } finally {
    loading.value = false;
  }
};

const updateSelected = async (item) => {
  try {
    const token = getToken();
    await axios.put(`${apiBase.value}/cart`, {
      productId: item.productId,
      selected: item.selected
    }, {
      headers: { Authorization: `Bearer  ${token}` }
    });
    fetchCartData(); // 立即刷新数据
  } catch (err) {
    ElMessage.error('更新选中状态失败');
  }
};

const updateQuantity = async (item, opcode) => {
  const original = item.quantity;
  try {
    const token = getToken();
    
    
    if(opcode === 1) {
      item.quantity++;
    } else {
      item.quantity = Math.max(1, item.quantity - 1);
    }
    
    await axios.put(`${apiBase.value}/cart/number`, {
      productId: item.productId,
      opcode: opcode
    }, {
      headers: { Authorization: `Bearer  ${token}` }
    });
    
  } catch (err) {
    // 失败时回滚
    item.quantity = original;
    ElMessage.error('更新数量失败');
  }
};

onMounted(() => {
  fetchCartData();
});
</script>

<style scoped>
.cart-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  cursor: pointer;
}

.product-name {
  font-size: 14px;
  line-height: 1.4;
  max-width: 250px;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-input {
  width: 80px;
}
</style>

